package org.xian.aio;

import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.*;

/**
 * @author : xian
 */
public class AIOServer {
    /** 服务端的 channel */
    private AsynchronousServerSocketChannel asyncServerSocketChannel;
    /** channel 的线程池 */
    private AsynchronousChannelGroup asyncChannelGroup;
    /** 端口号 */
    private int port = 8080;

    /** 线程池 */
    private ExecutorService executorService;

    public AIOServer() {
        try {
            this.executorService = Executors.newCachedThreadPool();
            this.asyncChannelGroup = AsynchronousChannelGroup.withCachedThreadPool(this.executorService, 1);
            this.asyncServerSocketChannel = AsynchronousServerSocketChannel.open(this.asyncChannelGroup);
            this.asyncServerSocketChannel.bind(new InetSocketAddress(this.port));
            // 有新的连接进来就会由操作系统调用 AIOServerHandler 进行处理
            this.asyncServerSocketChannel.accept(this, new AIOServerHandler());
            System.out.println("AIO Server Started ---");
            Thread.sleep(Integer.MAX_VALUE);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public AsynchronousServerSocketChannel getAsyncServerSocketChannel() {
        return asyncServerSocketChannel;
    }

    public static void main(String[] args) {
        new AIOServer();
    }
}
